package com.owo.springboot.service;

import com.owo.springboot.dto.AuthRequest;
import com.owo.springboot.dto.AuthResponse;
import com.owo.springboot.dto.RegisterRequest;
import com.owo.springboot.entity.User;
import com.owo.springboot.repository.UserRepository;
import com.owo.springboot.security.JwtService;
import com.owo.springboot.security.UserDetailsAdapter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用户认证服务
 * - 处理注册逻辑（密码加密）
 * - 处理登录逻辑（验证凭证并生成 Token）
 */
@Service
@RequiredArgsConstructor
public class AuthService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;
    private final AuthenticationManager authenticationManager;

    public ResponseEntity<?> register(RegisterRequest request) {
        // 校验用户名存在性
        if (userRepository.existsByUsername(request.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body("用户名已被注册");
        }

        // 校验邮箱存在性
        if (userRepository.existsByEmail(request.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body("邮箱已被注册");
        }

        // 密码加密存储
        User newUser = User.builder()
                .id(UUID.randomUUID().toString())
                .username(request.getUsername())
                .password(passwordEncoder.encode(request.getPassword()))
                .email(request.getEmail())
                .build();

        userRepository.save(newUser);

        return ResponseEntity.ok("注册成功");
    }


    public AuthResponse login(AuthRequest request) {
        // 调试：打印输入的用户名和密码
        System.out.println("尝试登录，用户名: " + request.getUsername() + "，密码: " + request.getPassword());
        System.out.println(passwordEncoder.encode(request.getPassword()));

        // Spring Security 自动验证密码
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
        );

        // 调试：验证用户是否加载成功
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        System.out.println("数据库中的加密密码: " + user.getPassword());

        // 生成 Token
        UserDetails userDetails = new UserDetailsAdapter(user);
        String jwtToken = jwtService.generateToken(userDetails);
        return AuthResponse.builder().token(jwtToken).build();
    }
}
